import Taro from '@tarojs/taro';
import { useEffect, useRef } from 'react';
import { useLoading } from './useLoading';

const defaultLoadingOptions = { title: '加载中' };

const useShowLoading = (
  loading,
  effects = Object.keys(loading.effects),
  { delay = 350, timeout = 5000, loadingOptions = defaultLoadingOptions, max = 0 } = {},
) => {
  const isLoading = useLoading(loading, effects, { delay, max });

  // 超时定时器
  const timer = useRef();

  // 是否显示 loading
  useEffect(() => {
    isLoading ? Taro.showLoading(loadingOptions) : Taro.hideLoading();

    clearTimeout(timer.current);
    if (isLoading) {
      timer.current = setTimeout(() => {
        Taro.hideLoading();

        console.warn(`loading ${timeout}ms timeout`, effects);
      }, timeout);
    }
  }, [isLoading, loadingOptions]);

  return isLoading;
};

export { useShowLoading };
